<?php
namespace Home\Controller;
use OT\DataDictionary;
/**
 * 微信控制器
 */
class WeixinController extends HomeController {
	//private $_TOKEN = 'chenll'; // 填写你设定的key,微信公众平台填写的key
	//private $_APPID ="wxcc3cb431ddc674c9";
	//private $_APPSECRET="ca8b60de5051895a1a3702b21cc2a4ad";
	
	public function getWeiChatResponse()
	{
		define("TOKEN", $this->_TOKEN);
 		//$this->createMenu();
 		//$this->getMenu();
		if (!isset($_GET['echostr'])) 
		{
			$this->responseMsg();
		}else
		{
			$this->valid();
		}
	}
	//构造函数，获取Access Token
	public function getConfigPara()
	{
		$this->lasttime = 1395049256;
		$this->access_token = "";
		if (time() > ($this->lasttime + 7200)){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					.$this->_APPID
					."&secret="
					.$this->_APPSECRET;
			$json=file_get_contents($url);
			$result=json_decode($json);
			//存储token
			$this->access_token = $result->access_token;
			$this->lasttime = time();
		}
	}
	//验证签名
	public function valid()
	{
		$echoStr = $_GET["echostr"];
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		if($tmpStr == $signature){
			echo $echoStr;
			exit;
		}
	}
	//响应消息
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$this->logger("R \r\n".$postStr);
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$RX_TYPE = trim($postObj->MsgType);
	
			if (($postObj->MsgType == "event") && ($postObj->Event == "subscribe" || $postObj->Event == "unsubscribe")){
				//过滤关注和取消关注事件
			}else{
			}
	
			//消息类型分离
			switch ($RX_TYPE)
			{
				case "event":
					$result = $this->receiveEvent($postObj);
					break;
				case "text":
					if (strstr($postObj->Content, "第三方")){
						$result = $this->relayPart3("http://www.fangbei.org/test.php".'?'.$_SERVER['QUERY_STRING'], $postStr);
					}else{
						$result = $this->receiveText($postObj);
					}
					break;
				case "image":
					$result = $this->receiveImage($postObj);
					break;
				case "location":
					$result = $this->receiveLocation($postObj);
					break;
				case "voice":
					$result = $this->receiveVoice($postObj);
					break;
				case "video":
					$result = $this->receiveVideo($postObj);
					break;
				case "link":
					$result = $this->receiveLink($postObj);
					break;
				default:
					$result = "unknown msg type: ".$RX_TYPE;
					break;
			}
			$this->logger("T \r\n".$result);
			echo $result;
		}else {
			echo "";
			exit;
		}
	}
	//接收事件消息
	private function receiveEvent($object)
	{
		$content = "";
		switch ($object->Event)
		{
			case "subscribe":
				$content = "欢迎关注CHENLL个人小站~ ";
				$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
				break;
			case "unsubscribe":
				$content = "取消关注";
				break;
			case "CLICK":
				switch ($object->EventKey)
				{
					case "COMPANY":
						$content = array();
						$content[] = array(
								"Title"=>"CHENLL工作室", 
								"Description"=>"", 
								"PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", 
								"Url" =>"http://m.cnblogs.com/?u=txw1958");
						break;
					default:
						$content = "点击菜单：".$object->EventKey;
						break;
				}
				break;
			case "VIEW":
				$content = "跳转链接 ".$object->EventKey;
				break;
			case "SCAN":
				$content = "扫描场景 ".$object->EventKey;
				break;
			case "LOCATION":
				$content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
				break;
			case "scancode_waitmsg":
				if ($object->ScanCodeInfo->ScanType == "qrcode")
				{
					$content = "扫码带提示：类型 二维码 结果：".$object->ScanCodeInfo->ScanResult;
				}else if ($object->ScanCodeInfo->ScanType == "barcode")
				{
					$codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
					$codeValue = $codeinfo[1];
					$content = "扫码带提示：类型 条形码 结果：".$codeValue;
				}else
				{
					$content = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
				}
				break;
			case "scancode_push":
				$content = "扫码推事件";
				break;
			case "pic_sysphoto":
				$content = "系统拍照";
				break;
			case "pic_weixin":
				$content = "相册发图：数量 ".$object->SendPicsInfo->Count;
				break;
			case "pic_photo_or_album":
				$content = "拍照或者相册：数量 ".$object->SendPicsInfo->Count;
				break;
			case "location_select":
				$content = "发送位置：标签 ".$object->SendLocationInfo->Label;
				break;
			default:
				$content = "receive a new event: ".$object->Event;
				break;
		}
	
		if(is_array($content)){
			if (isset($content[0]['PicUrl'])){
				$result = $this->transmitNews($object, $content);
			}else if (isset($content['MusicUrl'])){
				$result = $this->transmitMusic($object, $content);
			}
		}else{
			$result = $this->transmitText($object, $content);
		}
		return $result;
	}
	//接收文本消息
	private function receiveText($object)
	{
		$keyword = trim($object->Content);
		//多客服人工回复模式
		if (strstr($keyword, "请问在吗") 
		 || strstr($keyword, "在线客服"))
		{
			$result = $this->transmitService($object);
			return $result;
		} 
		//自动回复模式
		if (strstr($keyword, "文本"))
		{
			$content = "这是个文本消息";
		}
		else if (strstr($keyword, "表情"))
		{
			$content = "中国："
					.$this->bytes_to_emoji(0x1F1E8)
					.$this->bytes_to_emoji(0x1F1F3)
					."\n"
					."仙人掌："
					.$this->bytes_to_emoji(0x1F335);
		}
		else if (strstr($keyword, "单图文"))
		{
			$content = array();
			$content[] = array(
					"Title"=>"单图文标题",  
					"Description"=>"单图文内容", 
					"PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", 
					"Url" =>"http://m.cnblogs.com/?u=txw1958");
		}
		else if (strstr($keyword, "音乐"))
		{
			$content = array();
			$content = array(
					"Title"=>"最炫民族风", 
					"Description"=>"歌手：凤凰传奇", 
					"MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", 
					"HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
		
		}
		else if (strstr($keyword, "多图"))
		{
			$content = array();
			$pics=getLatestPics();
			for ($i=0; $i<count($pics); $i++)
			{
				$content[] = array(
						"Title"=>$pics[$i]['name'],
						"Description"=>$pics[$i]['discription'],
						"PicUrl"=>'http://'.$_SERVER['HTTP_HOST'].$pics[$i]['path'],
						"Url" =>'http://'.$_SERVER['HTTP_HOST'].$pics[$i]['path']);
			}
		//最新图片
		}
		else if (strstr($keyword, "新图"))
		{ 
			$pic=getLatestPic();
			$content = array();
			$content[] = array(
					"Title"=>$pic['name'],
					"Description"=>$pic['discription'],
					"PicUrl"=>'http://'.$_SERVER['HTTP_HOST'].$pic['path'],
					"Url" =>'http://'.$_SERVER['HTTP_HOST'].$pic['path']);
		//最新文章
		}
		else if (strstr($keyword, "新闻"))
		{ 
			$doc=getLatestDoc();
			$content = array();
			$content[] = array(
					"Title"=>$doc['title'],
					"Description"=>$doc['discription'],
					"PicUrl"=>'http://'.$_SERVER['HTTP_HOST'].get_cover($doc['cover_id'],'path'),
					"Url" =>'http://'.$_SERVER['HTTP_HOST'].U('Article/detail?id='.$doc['id']));
		}
		else if (strstr($keyword, "地址"))
		{ 
			$content ='http://'.$_SERVER['HTTP_HOST'].'/position.html';
			
		}
		else if ($keyword == 'HELP' 
				||$keyword == 'help' 
				||$keyword == '帮助' 
				||$keyword == '?' 
				||$keyword == '？')
		{ 
			$content =   "【提示】"
						."\n文本>>获取文本信息"
						."\n新闻>>获取网站最新文章"
						."\n新图>>获取网站最新图片"
						."\n地址>>查看公司地址"
						."\n表情>>表情符号"
						."\n单图文>>单图文模式"
						."\n多图文/图文>>图文模式"
						."\n音乐>>获取网站随机音乐" 
						."\n更多请访问zk.chenll.cn";
		}
		else
		{
			//小i聊天机器人接入
			$content = getXiaoiInfo($object->FromUserName, $keyword);
			//$result = $this->transmitText($object, $content);
			$content = $content."\n您可以发送【help/?】来查看帮助！";
		}
	
		if(is_array($content)){
			if (isset($content[0]))
			{
				$result = $this->transmitNews($object, $content);
			}
			else if (isset($content['MusicUrl']))
			{
				$result = $this->transmitMusic($object, $content);
			}
		}
		else
		{
			$result = $this->transmitText($object, $content);
		}
		return $result;
	}
	//接收图片消息
	private function receiveImage($object)
	{
		$content = array("MediaId"=>$object->MediaId);
		$result = $this->transmitImage($object, $content);
		return $result;
	}
	//接收位置消息
	private function receiveLocation($object)
	{
		$content ="经度：".$object->Location_Y."；"
				 ."\n纬度：".$object->Location_X."；"
				 ."\n缩放：".$object->Scale."；"
				 ."\n位置：".$object->Label;
		$result = $this->transmitText($object, $content);
		return $result;
	}
	//接收语音消息
	private function receiveVoice($object)
	{
		if (isset($object->Recognition) && !empty($object->Recognition)){
			$content = "你刚才说的是：".$object->Recognition;
			$result = $this->transmitText($object, $content);
		}else{
			$content = array("MediaId"=>$object->MediaId);
			$result = $this->transmitVoice($object, $content);
		}
		return $result;
	}
	//接收视频消息
	private function receiveVideo($object)
	{
		$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
		$result = $this->transmitVideo($object, $content);
		return $result;
	}
	//接收链接消息
	private function receiveLink($object)
	{
		$content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
		$result = $this->transmitText($object, $content);
		return $result;
	}
	
	//回复文本消息
	private function transmitText($object, $content)
	{
		if (!isset($content) || empty($content)){
			return "";
		}
		$xmlTpl = "<xml>
				    <ToUserName><![CDATA[%s]]></ToUserName>
				    <FromUserName><![CDATA[%s]]></FromUserName>
				    <CreateTime>%s</CreateTime>
				    <MsgType><![CDATA[text]]></MsgType>
				    <Content><![CDATA[%s]]></Content>
				</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
	
		return $result;
	}
	
	//回复图文消息
	private function transmitNews($object, $newsArray)
	{
		if(!is_array($newsArray)){
			return "";
		}
		$itemTpl ="<item>
			            <Title><![CDATA[%s]]></Title>
			            <Description><![CDATA[%s]]></Description>
			            <PicUrl><![CDATA[%s]]></PicUrl>
			            <Url><![CDATA[%s]]></Url>
			        </item>";
		$item_str = "";
		foreach ($newsArray as $item){
			$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
		}
		$xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[news]]></MsgType>
					<ArticleCount>%s</ArticleCount>
					<Articles>
					$item_str    </Articles>
					</xml>";
	
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
		return $result;
	}
	
	//回复音乐消息
	private function transmitMusic($object, $musicArray)
	{
		if(!is_array($musicArray)){
			return "";
		}
		$itemTpl = "<Music>
				        <Title><![CDATA[%s]]></Title>
				        <Description><![CDATA[%s]]></Description>
				        <MusicUrl><![CDATA[%s]]></MusicUrl>
				        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
				    </Music>";
		$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
		$xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[music]]></MsgType>
					$item_str
				   </xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复图片消息
	private function transmitImage($object, $imageArray)
	{
		$itemTpl = "<Image>
				        <MediaId><![CDATA[%s]]></MediaId>
				    </Image>";
		$item_str = sprintf($itemTpl, $imageArray['MediaId']);
		$xmlTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[image]]></MsgType>
						$item_str
				   </xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复语音消息
	private function transmitVoice($object, $voiceArray)
	{
		$itemTpl = "<Voice>
				        <MediaId><![CDATA[%s]]></MediaId>
				    </Voice>";
	
		$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
		$xmlTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[voice]]></MsgType>
				$item_str
				</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复视频消息
	private function transmitVideo($object, $videoArray)
	{
		$itemTpl = "<Video>
				        <MediaId><![CDATA[%s]]></MediaId>
				        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
				        <Title><![CDATA[%s]]></Title>
				        <Description><![CDATA[%s]]></Description>
				    </Video>";
	
		$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
	
		$xmlTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[video]]></MsgType>
					$item_str
					</xml>";
	
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复多客服消息
	private function transmitService($object)
	{
		$xmlTpl = "<xml>
					    <ToUserName><![CDATA[%s]]></ToUserName>
					    <FromUserName><![CDATA[%s]]></FromUserName>
					    <CreateTime>%s</CreateTime>
					    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
					</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	
	//回复第三方接口消息
	private function relayPart3($url, $rawData)
	{
		$headers = array("Content-Type: text/xml; charset=utf-8");
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
		$output = curl_exec($ch);
		curl_close($ch);
		return $output;
	}
	
	//字节转Emoji表情
	function bytes_to_emoji($cp)
	{
		if ($cp > 0x10000){       # 4 bytes
			return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
		}else if ($cp > 0x800){   # 3 bytes
			return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
		}else if ($cp > 0x80){    # 2 bytes
			return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
		}else{                    # 1 byte
			return chr($cp);
		}
	}
	
	//日志记录
	private function logger($log_content)
	{
		if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
			sae_set_display_errors(false);
			sae_debug($log_content);
			sae_set_display_errors(true);
		}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
			$max_size = 1000000;
			$log_filename = "log.xml";
			if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
			file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
		}
	}
	
	/********************
	 *微信菜单管理
	 ********************/
	public function test()
	{
		$this->getConfigPara();
		$this->createMenu();
	}
	function getMenu2() 
	{
		$menuPostString ='{"button":[{"name":"方倍工作室","sub_button":[{"type":"click","name":"公司简介","key":"公司简介"},{"type":"click","name":"社会责任","key":"社会责任"},{"type":"click","name":"联系我们","key":"联系我们"}]},{"name":"产品服务","sub_button":[{"type":"click","name":"微信平台","key":"微信平台"},{"type":"click","name":"微博应用","key":"微博应用"},{"type":"click","name":"手机网站","key":"手机网站"}]},{"name":"技术支持","sub_button":[{"type":"click","name":"文档下载","key":"文档下载"},{"type":"click","name":"技术社区","key":"技术社区"},{"type":"click","name":"服务热线","key":"服务热线"}]}]}';;
		//通过访问weixin接口获取动态的access_token
		$url = "https://api.weixin.qq.com/cgi-bin/token"
				."?grant_type=client_credential"
				."&appid=".$this->_APPID
				."&secret=".$this->_APPSECRET;
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		
		$output = curl_exec($ch);
		curl_close($ch);
		if (empty($output)) { var_dump($output); exit; }
		$result = json_decode($output);
		$token = $result->access_token;
		
		//创建菜单并返回微信
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$token";
		//$jsonData = file_get_contents("menu.json");
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		//curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $menuPostString);
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		$output = curl_exec($ch);
		curl_close($ch);
		var_dump($output);
		//var_dump($this->create_menu($menuPostString));
	}
	function createMenu()
	{
		$data='{
		 "button":[
		 {
			   "name":"公共查询",
			   "sub_button":[
				{
				   "type":"click",
				   "name":"天气查询",
				   "key":"tianQi"
				},
				{
				   "type":"click",
				   "name":"快递查询",
				   "key":"kuaiDi"
				}]
		  },
		  {
			   "name":"苏州本地",
			   "sub_button":[
				{
				   "type":"click",
				   "name":"苏州景点",
				   "key":"suzhouScenic"
				},
				{
				   "type":"click",
				   "name":"住在苏州",
				   "key":"liveSuzhou"
				}]
		   },
		   {
			   "type":"view",
			   "name":"联系我们",
			   "url":"http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5NDM0NTEyMg==&appmsgid=10000021&itemidx=1&sign=e25db2fe9750a1b08788d6a7c0498562#wechat_redirect"
		   }]
       }';
		
		$MENU_URL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
		
		$ch = curl_init($MENU_URL);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
		$info = curl_exec($ch);
		$menu = json_decode($info);
		print_r($info);		//创建成功返回：{"errcode":0,"errmsg":"ok"}
		
		if($menu->errcode == "0"){
			echo "菜单创建成功";
		}else{
			echo "菜单创建失败";
		}
	}
	function getMenu()
	{
		$MENU_URL="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token;
		$cu = curl_init();
		curl_setopt($cu, CURLOPT_URL, $MENU_URL);
		curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1);
		$menu_json = curl_exec($cu);
		$menu = json_decode($menu_json);
		curl_close($cu);
		echo $menu_json;
	}
	function deleteMenu()
	{
		$MENU_URL="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
		$cu = curl_init();
		curl_setopt($cu, CURLOPT_URL, $MENU_URL);
		curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1);
		$info = curl_exec($cu);
		$res = json_decode($info);
		curl_close($cu);
		if($res->errcode == "0"){
			echo "菜单删除成功";
		}else{
			echo "菜单删除失败";
		}
	}
	/*********************
	 *其他功能（目前均无权限）
	 ********************/
	//获取关注者列表
	public function get_user_list($next_openid = NULL)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
		$res = $this->https_request($url);
		return json_decode($res, true);
	}
	//获取微信服务器地址
	public function get_wechatip()
	{
		$url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$this->access_token;
		$res = $this->https_request($url);
		return json_decode($res, true);
	}
	//获取用户基本信息
	public function get_user_info($openid)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
		$res = $this->https_request($url);
		return json_decode($res, true);
	}
	//创建菜单
	public function create_menu($data)
	{
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
		$res = $this->https_request($url, $data);
		return json_decode($res, true);
	}
	//发送客服消息，已实现发送文本，其他类型可扩展
	public function send_custom_message($touser, $type, $data)
	{
		$msg = array('touser' =>$touser);
		switch($type)
		{
			case 'text':
				$msg['msgtype'] = 'text';
				$msg['text']    = array('content'=> urlencode($data));
				break;
		}
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
		return $this->https_request($url, urldecode(json_encode($msg)));
	}
	//生成参数二维码
	public function create_qrcode($scene_type, $scene_id)
	{
		switch($scene_type)
		{
			case 'QR_LIMIT_SCENE': //永久
				$data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
				break;
			case 'QR_SCENE':       //临时
				$data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
				break;
		}
		$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
		$res = $this->https_request($url, $data);
		$result = json_decode($res, true);
		return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
	}
	//创建分组
	public function create_group($name)
	{
		$data = '{"group": {"name": "'.$name.'"}}';
		$url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
		$res = $this->https_request($url, $data);
		return json_decode($res, true);
	}
	//移动用户分组
	public function update_group($openid, $to_groupid)
	{
		$data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
		$url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
		$res = $this->https_request($url, $data);
		return json_decode($res, true);
	}
	//上传多媒体文件
	public function upload_media($type, $file)
	{
		$data = array("media"  => "@".dirname(__FILE__).'\\'.$file);
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
		$res = $this->https_request($url, $data);
		return json_decode($res, true);
	}
	//https请求（支持GET和POST）
	protected function https_request($url, $data = null)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}

	/*********************
	 *小i聊天机器人接入
	 ********************/
	private function testgetXiaoiInfo($object)
	{
		$keyword = trim($object->Content);
		$content = getXiaoiInfo($object->FromUserName, $keyword);
		$result = $this->transmitText($object, $content);
		return $result;
	}
 
}